<template>
  <div class="video-container">
    <video id="video" autoPlay style="border-radius: 8px;"
           v-show="isShowVideo"></video>
    <canvas id="canvas" style="border-radius: 8px;"
            v-show="isShowCanvas"></canvas>
  </div>
</template>

<script>
import {getCurrentInstance, ref} from "vue";

export default {
  name: "mine-face",
  setup() {
    const isShowVideo = ref(false)
    const isShowCanvas = ref(false)
    const isCameraOpen = ref(false)
    const mediaStreamTrack = ref(null) 	// 全局视频对象
    const {proxy} = getCurrentInstance()

    const openFace = () => {
      // 如果摄像头已经打开了，就不再继续下方代码业务
      if (isCameraOpen.value) {
        return;
      }
      let constraints = {
        video: {width: 315, height: 150},
        audio: false // 是否使用麦克风
      };
      // 获得video摄像头
      let video = document.getElementById('video');
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
          if (!getUserMedia) {
            return Promise.reject(new Error("getUserMedia is not implemented in this browser"));
          }
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      navigator.mediaDevices.getUserMedia(constraints).then((mediaStream) => {
        mediaStreamTrack.value = mediaStream.getVideoTracks()
        video.srcObject = mediaStream;
        video.play();
      }).catch((err) => {
        ElMessage.error("没有开启摄像头权限或浏览器版本不兼容");
      });
      video.onloadedmetadata = function () {
        isCameraOpen.value = true;
      };
      isShowVideo.value = true
      isShowCanvas.value = false
    }
    const closeFace = () => {
      let stream = document.getElementById('video').srcObject;
      if (stream == null) {
        return;
      }
      let tracks = stream.getTracks();
      tracks.forEach(function (track) {
        track.stop();
      });
      document.getElementById('video').srcObject = null;
      isShowVideo.value = false
      isShowCanvas.value = true
      isCameraOpen.value = false
    }
    proxy.$bus.on('openFace', data => {
      openFace()
    })
    proxy.$bus.on('closeFace', data => {
      closeFace()
    })
    return {
      isShowVideo,
      isShowCanvas
    }
  }
}
</script>

<style lang="scss" scoped>


</style>
